import { getImageUrl, request } from "./utils";
import { tokenKey } from '/config';

// import { request } from '/utils';
App({
    globalData: {
        userInfo: null,
        sysInfo: null
    },
    onLaunch(options) {
        my.setCanPullDown({ canPullDown: false });
        const sysInfo = my.getSystemInfoSync();
        this.globalData.sysInfo = sysInfo;
        // const {
        //     statusBarHeight,
        //     titleBarHeight,
        // } = sysInfo;
    },
    async login(cb) {
        return new Promise((resolve, reject) => {
            my.showLoading({ content: '登录中' });
            my.getAuthCode({
                scopes: ['auth_user'],
                success: async ({ authCode }) => {
                    try {
                        const { code, data: { userInfo, ...tokenInfo } = {} } = await request.post(
                            '/miniapp/user/login', { authCode });
                        if (code === 200) {
                            my.showToast({ type: 'success', content: '登录成功' })
                            my.setStorageSync({
                                key: tokenKey,
                                data: tokenInfo
                            });
                            my.setStorageSync({
                                key: 'userInfo',
                                data: userInfo
                            });
                            cb && cb(userInfo);
                            this.globalData.userInfo = userInfo;
                            resolve();
                        } else {
                            reject();
                        }
                    } catch (error) {
                        reject(error);
                    } finally {
                        my.hideLoading();
                    }
                },
                fail: () => {
                    my.hideLoading();
                    reject();
                }
            })
        })
    },
    async getUserInfo(cb) {
        const { code, data: userInfo } = await request.get('/miniapp/user/userInfo');
        if (code === 200) {
            const { avatar } = userInfo;
            const formattedUserInfo = { ...userInfo, avatar: getImageUrl(avatar) };
            this.globalData.userInfo = formattedUserInfo
            cb && cb(formattedUserInfo);
        };
    },
});